package simulation;

import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import forces.CenterOfMassForce;
import forces.Force;
import forces.Gravity;
import forces.Viscosity;
import forces.WallRepulsionBottom;
import forces.WallRepulsionLeft;
import forces.WallRepulsionRight;
import forces.WallRepulsionTop;


/**
 * The ForceToggler has the responsibility to turn forces on or off based on
 * key press.
 */
public class ForceToggler {

    private Map<Integer, Class<?>> myKeyMap;

    /**
     * Creates a ForceToggler and initializes myKeyMap
     */
    public ForceToggler () {
        initMap();
    }

    /**
     * Attempts to turn a force off if it exists. Otherwise turns it on.
     */
    public void update (List<Force> forces, int key) {
        if (myKeyMap.containsKey(key)) {
            Class<?> className = myKeyMap.get(key);
            if (toggleOff(className, forces)) {
                return;
            }
            else {
                try {
                    forces.add((Force) className.newInstance());
                }
                catch (InstantiationException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Turns a force off. Returns whether it was successful.
     */
    private boolean toggleOff (Class<?> className, List<Force> forces) {
        for (Force f : forces) {
            if (f.getClass().equals(className)) {
                forces.remove(f);
                return true;
            }
        }
        return false;
    }

    /**
     * Creates a map of key presses to Force classes.
     */
    private void initMap () {
        myKeyMap = new HashMap<Integer, Class<?>>();
        myKeyMap.put(KeyEvent.VK_G, Gravity.class);
        myKeyMap.put(KeyEvent.VK_V, Viscosity.class);
        myKeyMap.put(KeyEvent.VK_M, CenterOfMassForce.class);
        myKeyMap.put(KeyEvent.VK_1, WallRepulsionTop.class);
        myKeyMap.put(KeyEvent.VK_2, WallRepulsionRight.class);
        myKeyMap.put(KeyEvent.VK_3, WallRepulsionBottom.class);
        myKeyMap.put(KeyEvent.VK_4, WallRepulsionLeft.class);
    }
}
